package com.xyzwps.ewa.modules.auth.session

import com.xyzwps.ewa.common.ServerException
import com.xyzwps.ewa.data.database
import io.ktor.http.*
import org.jetbrains.exposed.sql.transactions.transaction

object RdbSessionStorage : SessionStorage<Session> {
    override fun invalidate(id: String) {
        transaction {
            RdbSessionRepository.delete(id)
        }
    }

    override fun get(id: String): Session? = transaction {
        RdbSessionRepository.find(id)
    }

    override fun set(id: String, session: Session) {
        if (session.sessionId != id) {
            throw ServerException("Maybe a bug!", HttpStatusCode.InternalServerError)
        }
        transaction {
            val oldSession = RdbSessionRepository.find(session.sessionId)
            if (oldSession == null) {
                RdbSessionRepository.create(session)
            } else {
                RdbSessionRepository.update(session)
            }
        }
    }
}